<template>
  <div class="center_bottom">
    <div class="select">
      <div>
        <span>IO通道:</span>
        <el-select v-model="channel" placeholder="请选择" style="margin-left: 5px" size="mini" @change="onChannelChange">
          <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div>
        <span>信道:</span>
        <el-input
            type="number"
            @blur="getData"
            size="mini"
            style="display: inline-block;width: 80px;margin-left: 5px"
            placeholder="请输入信道"
            v-model="address">
        </el-input>
      </div>
    </div>
    <div class="power_control" v-if="hasCache">
      <div class="item" v-for="(item,index) in controlList">
        <div class="power close" v-if="item === '0' && !loadingArray[index]">
          <svg class="iconfont index" aria-hidden="true">
            <use :xlink:href="`#icon-xuhao_${index + 1}`"></use>
          </svg>
          <svg class="iconfont switch" aria-hidden="true">
            <use xlink:href="#icon-dianyuan1" @click="openPower(index)"></use>
          </svg>
        </div>
        <div class="power open" v-else-if="item === '1' && !loadingArray[index]">
          <svg class="iconfont index" aria-hidden="true">
            <use :xlink:href="`#icon-xuhao_${index + 1}`"></use>
          </svg>
          <svg class="iconfont switch" aria-hidden="true">
            <use xlink:href="#icon-dianyuan11" @click="closePower(index)"></use>
          </svg>
        </div>
        <div class="power loading" v-else>
          <svg class="iconfont index" aria-hidden="true">
            <use :xlink:href="`#icon-xuhao_${index + 1}`"></use>
          </svg>
          <i class="el-icon-loading icon" style="color: white;font-size: 60px;"></i>
        </div>
      </div>
    </div>
    <div class="null" v-else>
      缓存数据为空
    </div>
  </div>
</template>

<script>
import moment from "moment/moment";
import axios from "axios";

export default {
  data() {
    return {
      timer: null,
      data: null,
      controlList:[],
      hasCache: false,
      channel: "d4ad2070b92f0002", // 默认选择新的通道
      channelOptions:[],
      address: 1,
      loadingArray: [false,false,false,false,false,false],
    };
  },
  watch:{
    '$store.state.setting.channelOptionStore':{
      handler () {
        if(this.$store.state.setting.channelOptionStore.length > 0){
          let re = true;
          this.$store.state.setting.channelOptionStore.forEach(item=>{
            if(item[1] === 'd4ad2070b92f0000' || item[1] === 'd4ad2070b92f0001' || item[1] === 'd4ad2070b92f0002'){
              re = false
            }
          })
          if (re){
            this.channel = this.$store.state.setting.channelOptionStore[0][1];
          }
        }
      },
      deep: true
    }
  },
  beforeDestroy() {
    this.clearData();
  },
  mounted() {
    this.getData();
    this.timer = setInterval(()=>{
      this.getData();
    },3000)
  },
  methods: {
    async getData(){
      this.data = await axios.get(`${process.env.VUE_APP_HOST}/relay/list`);
      const keyArray = Object.keys(this.data);
      if(!this.address){
        //key为空
        if(keyArray.length > 0){
          this.address = Object.keys(this.data)[0];
        }
      }else{
        //key不为空
        let has = true;
        for (let i = 0; i < keyArray.length; i++) {
          if(JSON.stringify(this.address) === keyArray[i].split('-')[1]){
            has = false;
            break
          }
        }
        if(has){
          //信道不存在的时候，尝试查询新的通道
          await axios.get(`${process.env.VUE_APP_HOST}/relay/doCacheSearch?address=${this.address}&doNumber=6&channelName=${this.channel}`)
          return;
        }
      }

      this.channelOptions = []
      if(this.$store.state.setting.channelOptionStore.length == 0){
        await this.getOptionData();
      }
      // await this.getOptionData();
      const option = this.$store.state.setting.channelOptionStore;
      // console.log(option,"option")
      option.forEach(item=>{
        if(item[1].startsWith('d')){
          this.channelOptions.push({
            label:item[1],
            value:item[1]
          })
        }
      })

      this.analysis();
    },
    async getOptionData() {
      const res = await axios.get(`${process.env.VUE_APP_HOST}/channel/list`);
      const array = Object.entries(res)
      // console.log(array,"array")
      array.forEach(item=>{
        item[0] = item[0].slice(1);
      })
      this.$store.state.setting.channelOptionStore = array;
    },
    //解析数据
    analysis(){
      this.controlList = []
      let charArray = []
      if(this.address){
        let energizeIndex = 0;
        const binary = this.data[`${this.channel}-${this.address}`].slice(0,-2);
        charArray = binary.split('');
        charArray.forEach(item=>{
          if(item === '1' || item === 1){
            energizeIndex++;
          }
        })
        this.$store.state.setting.energizeIndex = energizeIndex;
        // console.log(this.$store.state.setting.energizeIndex, energizeIndex)
        this.controlList = charArray;
        this.hasCache = true;
      }else{
        this.hasCache = false;
      }
    },
    clearData() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    openPower(index){
      this.loadingArray[index] = true;
      const param = {
        address:this.address,
        channelName:this.channel,
        doNumber:index + 1,
        f:true
      }
      axios.post(`${process.env.VUE_APP_HOST}/relay/doControl`,param)
      this.$forceUpdate();
      setTimeout(()=>{
        this.loadingArray[index] = false;
        this.$forceUpdate();
      },3000)
    },
    closePower(index){
      this.loadingArray[index] = true;
      const param = {
        address:this.address,
        channelName:this.channel,
        doNumber:index + 1,
        f:false
      }
      axios.post(`${process.env.VUE_APP_HOST}/relay/doControl`,param)
      this.$forceUpdate();
      setTimeout(()=>{
        this.loadingArray[index] = false;
        this.$forceUpdate();
      },3000)
    },
    // 通道切换事件
    onChannelChange(value) {
      this.channel = value;
      this.getData(); // 重新获取数据
    },
  }
};
</script>
<style lang="scss" scoped>
.center_bottom {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .select {
    display: flex;
    width: 100%;
    height: auto;
    justify-content: space-evenly;
  }

  .power_control{
    display: flex;
    width: 100%;
    height: 100%;
    flex-wrap: wrap;

    .item{
      display: flex;
      width: 33%;
      align-items: center;
      justify-content: center;

      .power{
        .switch{
          font-size: 60px;
          cursor: pointer;
        }

        .index{
          font-size: 24px;
          position: relative;
          bottom: -20px;
          left: 0px;
        }

        .switch{
          transition: transform 0.3s ease; /* 平滑过渡效果 */
          transform: scale(1); /* 默认不放大 */
        }

        .switch:hover{
          transform: scale(1.15); /* 放大15% */
        };
      }

    }
  }
}
</style>


